/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.factorial;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;

/**
 * Creates a newly configured {@link ChannelPipeline} for a server-side channel.
 * 服务端 Pipeline config
 */
public class FactorialServerInitializer extends ChannelInitializer<SocketChannel> {

    private final SslContext sslCtx;

    public FactorialServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        /**
         * 取得 pipeline
         */
        ChannelPipeline pipeline = ch.pipeline();

        if (sslCtx != null) {
            /**
             * 如果为ssl , 则优先配置 ssl处理器
             */
            pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        }

        /**
         * 添加日志处理器
         */
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        // Enable stream compression (you can remove these two if unnecessary)
        /**
         * 客户端配置压缩/解压缩. 服务端必须同步配置
         */
        pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
        pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));

        // Add the number codec first,
        /**
         * 客户端配置了 编码/ 解码器.服务端必须一样配置
         */
        pipeline.addLast(new BigIntegerDecoder());
        pipeline.addLast(new NumberEncoder());

        // and then business logic.
        // 这里添加业务逻辑处理
        // Please note we create a handler for every new channel
        // 这里请注意 , 这里是创建一个新的实例对象的处理器
        // because it has stateful properties.
        // 因为处理器是有状态的 ,不能与其他channel内的混用
        FactorialServerHandler factoialServerHandler = new FactorialServerHandler();
        pipeline.addLast(factoialServerHandler);
    }
}
